package com.yc.shopping.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.yc.shopping.util.DBHelper;

public class GoodsDao {
	
	/**
	 * 查看所有
	 * @throws SQLException 
	 */
	
	public List<Map<String, Object>> findAll() throws SQLException{
		String sql ="select gid,gname,gcode,g.tid,gmark,gimage,unit,weight,balance,gdate,price,saleprice,gstate,tname from tb_goods g,tb_goodtype gt where g.tid = gt.tid order by gid";
		return DBHelper.selectListMap(sql);
	}
	
	/**
	 * 根据类型名称查看所有
	 * @return
	 * @throws SQLException
	 */
	public List<Map<String, Object>> findByTname(String tname) throws SQLException{
		String sql ="select gid,gname,gcode,g.tid,gmark,gimage,unit,weight,balance,gdate,price,saleprice,gstate,tname from tb_goods g,tb_goodtype gt where g.tid = gt.tid and tname = ?";
		return DBHelper.selectListMap(sql,tname);
	}
	
	/**
	 * 根据条形码或id查询
	 * @param tname
	 * @return
	 * @throws SQLException
	 */
	public Map<String, Object> findByIdOrCode(String code) throws SQLException{
		
		String sql ="select gid,gname,gcode,g.tid,gmark,gimage,unit,weight,balance,gdate,price,saleprice,gstate,tname from tb_goods g,tb_goodtype gt where g.tid = gt.tid and gid = ?";
		String sql2 ="select gid,gname,gcode,g.tid,gmark,gimage,unit,weight,balance,gdate,price,saleprice,gstate,tname from tb_goods g,tb_goodtype gt where g.tid = gt.tid and gcode = ?";
		
		Map<String, Object> map = DBHelper.selectOneMap(sql2, code);
		if(map == null) {
			return DBHelper.selectOneMap(sql,code);
		}else {
			return map;
		}
	}
	/**
	 * 添加商品信息
	 * @param gname
	 * @param gcode
	 * @param tid
	 * @param gmark
	 * @param gimage
	 * @param unit
	 * @param weight
	 * @param balance
	 * @param gdate
	 * @param price
	 * @param saleprice
	 * @return
	 * @throws SQLException
	 */
	public int add (String gname,String gcode,String tid,
			String gmark,String gimage, String unit, String weight, int balance,String gdate, float price, float saleprice) throws SQLException {
		String sql = "insert into tb_goods values(?,?,?,?,?,?,?,?,?,?,?,?,1)";
		Integer gid=Integer.valueOf(DBHelper.selectOneMap("select max(gid) mgid from tb_goods").get("MGID").toString());
		return DBHelper.update(sql,gid+1, gname,gcode,tid,gmark,gimage,unit,weight,balance,gdate,price,saleprice);
	}

	public int updateBalance(int gid,int num) throws SQLException {
		String sql = "update tb_goods set balance = balance+ ? where gid = ?";
		return DBHelper.update(sql, num,gid);
	}
}
